package file;

import example.FileUpload;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Arrays;

/**
 * 支绍昆 2018/10/15 0015
 */
public class FileDownLoadClientHandler extends ChannelInboundHandlerAdapter {

    /*
     *   文件路径
     */
    private String file;
    private int start;
    private RandomAccessFile randomAccessFile;

    private int i = 0;

    public FileDownLoadClientHandler(String file){
        this.file = file;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("channel active");

        /*
        请求服务器 所要下载的文件
         */
        ctx.writeAndFlush(file);
        System.out.println("request server down file : " + file);
        randomAccessFile = new RandomAccessFile(new File(file),"rw");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channel read");
        System.out.println("from server : " + msg);

        /*
        保存文件内容
         */
        if (msg instanceof FileUpload){
            FileUpload fileUpload = (FileUpload) msg;
            int read = fileUpload.getEndPos();

            //写文件
            randomAccessFile.seek(start);
            randomAccessFile.write(fileUpload.getBytes());

            System.out.println(fileUpload.getBytes());
            //save

            //返回文件起点
            start = start + read;

            if (read > 0){
                ctx.writeAndFlush(start);
                if (read != 1024 * 10){
                    randomAccessFile.close();
                    ctx.close();

                }
            }else {
                randomAccessFile.close();
                ctx.close();
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("channel inactive");
    }
}
